package security;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;


import sd1.security.Digest;
import sd1.security.KeyPair;
import sd1.security.PrivateKey;
import sd1.security.PublicKey;

public class CertificateEntity {

	private String name;
	private PublicKey pubkey;
	private PrivateKey privkey;
	
	public CertificateEntity(){
		this.name = "CertificationEntity A&J";
		KeyPair pair = KeyPair.createKeyPair();
		this.pubkey = pair.getPublic();
		this.privkey = pair.getPrivate();
	}
	
	public void makeCertificate(String certName){
		Digest dig = null;
		KeyPair p = KeyPair.createKeyPair();
		try {
			dig = Digest.createDigest();
			dig.update(certName.getBytes());
			dig.update(p.getPublic().exportKey());
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Não conseguiu criar o digest!");
		}
		byte[] digest = privkey.encrypt(dig.getDigest());
		PrivateCert pvc = new PrivateCert(p.getPublic().exportKey(), p.getPrivate().exportKey(), pubkey.exportKey(), digest, certName);		
		
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(certName+"_Cert"));
			oos.writeObject(pvc);
			oos.flush();
			oos.close();
		} catch (IOException e) {
			System.out.println("Não conseguiu escrever no ficheiro!");
		}
		System.out.println(certName);
	}
}
